package mspbots.hubspot.data.core.properties;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.hubspot.common.ResultMsg;
import mspbots.hubspot.data.core.BaseReceiver;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * mspbots.data.sync.autotask.badmessage.BadMessageReceiver
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/7/21
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class PropertiesReceiver extends BaseReceiver {

    private final PropertiesRepository propertiesRepository;

    @RabbitListener(queues = "hub-spot.entity-properties.sync", concurrency = "2")
    public void syncTask(ResultMsg content) {

        Property property = Property.builder().name(content.getEntity().get("name").textValue())
                .type(content.getAction())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();

        this.propertiesRepository.findByTenantIdAndTypeAndName(content.getTenantId(), content.getAction(), property.getName())
                .map(ticket -> {
                    property.setId(ticket.getId());
                    return property;
                })
                .defaultIfEmpty(property)
                .flatMap(this.propertiesRepository::save)
                .block(Duration.ofSeconds(10));

    }

}
